//
//  PhoneNumberController.m
//  智慧小区
//
//  Created by lab603 on 15/6/30.
//  Copyright (c) 2015年 Dreamsoul. All rights reserved.
//

#import "PhoneNumberController.h"
#import "PhoneFrame.h"
#import "Phone.h"
#import "PPHttpTool.h"
#import "APIClient.h"
#import "MJExtension.h"
#import "phoneHistoryCell.h"
@interface PhoneNumberController ()<UIAlertViewDelegate>
//保存电话模型的数组
@property (nonatomic,strong)NSMutableArray *phoneArray;
//为了实现拨打电话完成后返回应用，所添加webView
@property (nonatomic,strong)UIWebView *webView;
@end

@implementation PhoneNumberController
- (NSMutableArray *)phoneArray{
    if (_phoneArray==nil) {
        _phoneArray = [NSMutableArray array];
    }
    return _phoneArray;
}
- (id)init{
    self = [super init];
    if (self) {
        self.title = @"常用电话";
        self.view.backgroundColor = APP_BACK_COLOR;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //获得常用电话数据
    [self getPhoneData];
}
/**
 *  获得常用电话数据
 */
- (void)getPhoneData{
    NSString *urlString = [APIClient relativePathForPhoneNumber];
    [PPHttpTool getWithURL:urlString params:nil success:^(id json) {
        IWLog(@"%@",json);
        NSArray *tempArray = [Phone objectArrayWithKeyValuesArray:json];
        for (int i=0; i<tempArray.count; i++) {
            Phone *phone = tempArray[i];
            PhoneFrame *phoneF = [[PhoneFrame alloc] init];
            phoneF.phone = phone;
            [self.phoneArray addObject:phoneF];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.phoneArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PhoneFrame *phoneF = self.phoneArray[indexPath.row];
    phoneHistoryCell *cell = [phoneHistoryCell cellWithTableView:tableView];
    cell.phoneFrame = phoneF;
    [cell setTapPhonePlayBlock:^(PhoneFrame *phoneFrame) {
        Phone *phone = phoneFrame.phone;
        if (_webView == nil) {
            _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        }
        NSString *telString = [NSString stringWithFormat:@"%@%@",@"tel://",phone.phone];
        
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telString]]];
    }];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PhoneFrame *phoneF = self.phoneArray[indexPath.row];
    return phoneF.cellHeight;
} 
@end

